package vip.hello520.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.hello520.service.LoginService;
import vip.hello520.model.UserPo;

import java.util.HashSet;
import java.util.Set;

@Service
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private LoginService loginService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        UserPo userPo = (UserPo) principalCollection.getPrimaryPrincipal();

        Set<String> roleListByUserId = new HashSet<>();
        Set<String> powerListByUserId = new HashSet<>();

        try {

            roleListByUserId = loginService.getRolePoListByUserId(userPo.getId());
            powerListByUserId = loginService.getPowerPoListByUserId(userPo.getId());

        } catch (Exception e) {
            e.printStackTrace();
        }

        info.setRoles(roleListByUserId);
        info.setStringPermissions(powerListByUserId);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        UserPo user = null;
        try {
            user = loginService.getUserPoByName(token.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //盐值
        ByteSource salt = ByteSource.Util.bytes(user.getUsername());
        AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), salt, this.getName());
        return info;
    }
}
